package com.boang.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.boang.domain.po.Users;
import com.boang.domain.vo.UsersVO;
import com.boang.resp.Result;
import com.boang.service.UsersService;
import com.boang.mapper.UsersMapper;
import com.boang.utils.JwtTokenUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.util.Objects;

/**
 * @author 13813
 * @description 针对表【users(用户表)】的数据库操作Service实现
 * @createDate 2024-09-06 11:07:09
 */
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users>
        implements UsersService {

    @Autowired
    private JwtTokenUtils jwtTokenUtils;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public String loginWithVerificationCode(UsersVO usersVO) throws UnsupportedEncodingException {
        //从redis中根据key取出验证码
        String code = redisTemplate.opsForValue().get("code:" + usersVO.getPhone());

        if (usersVO.getCode().equals(code)) {
            return jwtTokenUtils.generateToken(usersVO.getPhone());
        }
        return null;
    }

    @Override
    public String loginWithUsernameAndPassword(UsersVO usersVO) throws UnsupportedEncodingException {
        LambdaQueryWrapper<Users> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Users::getUsername, usersVO.getUsername());
        Users users = this.getOne(lambdaQueryWrapper);

        if (Objects.isNull(users)) {
            throw new RuntimeException("没有此用户");
        }

        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(usersVO.getPasswordHash());

        if (passwordEncoder.matches(encode, users.getPasswordHash())) {
            return jwtTokenUtils.generateToken(users.getUsername());
        }
        return null;
    }
}




